<template>
  <div class="login-log-page art-full-height">
    <!-- 搜索栏 -->
    <div class="search-bar mb-4">
      <el-form ref="searchFormRef" :model="searchForm" :inline="true" label-width="auto">
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="searchDateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.logUserName" 
            placeholder="请输入用户名" 
            clearable 
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input 
            v-model="searchForm.logIp" 
            placeholder="请输入IP地址" 
            clearable 
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select 
            v-model="searchForm.logType" 
            placeholder="请选择操作类型" 
            clearable
            class="search-item"
          >
            <el-option label="登录成功" :value="1"></el-option>
            <el-option label="退出登录" :value="2"></el-option>
            <el-option label="密码错误" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>

      <!-- 登录日志详情弹窗 -->
    <LoginLogSearchDialog 
      v-model="detailDialogVisible"
      title="登录日志详情"
      :data="detailData"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, watch, h, onMounted } from 'vue'
  import { useTable } from '@/composables/useTable'
  import { apiLogLoginPageDataUsingPost, apiLogLoginGetDataUsingPost } from '@/api/apIdenglurizhi'
  import type { ApiLogLoginBoApiLogLoginPageData, ApiLogLoginBoApiLogLoginGetData } from '@/api/types'
  import LoginLogSearchDialog from './module/login-log-search-dialog.vue'
  import { View } from '@element-plus/icons-vue'


  defineOptions({ name: 'LoginLog' })

  // 搜索表单
  const searchFormRef = ref()
  const searchForm = reactive({
    logUserName: '',
    logIp: '',
    logExecuteTimeBegin: '',
    logExecuteTimeEnd: '',
    logType: null as number | null
  })
  
  const searchDateRange = ref<[string, string]>(['', ''])

  // 详情弹窗
  const detailDialogVisible = ref(false)
  const detailData = ref<any>({})

  // 格式化日期时间
  const formatDateTime = (datetime: string) => {
    if (!datetime) return ''
    
    // 处理 "20251029160020" 格式
    if (datetime.length === 14 && /^\d{14}$/.test(datetime)) {
      const year = datetime.substring(0, 4)
      const month = datetime.substring(4, 6)
      const day = datetime.substring(6, 8)
      const hour = datetime.substring(8, 10)
      const minute = datetime.substring(10, 12)
      const second = datetime.substring(12, 14)
      
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }
    
    // 处理标准日期格式
    const date = new Date(datetime)
    if (isNaN(date.getTime())) return datetime // 如果日期无效，返回原始值
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 获取操作类型描述
  const getLogTypeText = (logType: number) => {
    switch (logType) {
      case 1:
        return '登录成功'
      case 2:
        return '退出登录'
      case 3:
        return '密码错误'
      default:
        return '未知操作'
    }
  }

  // 获取设备类型描述
  const getDeviceTypeText = (isMobile: number) => {
    return isMobile === 0 ? '是' : '否'
  }

  // 监听日期范围变化
  watch(searchDateRange, (newVal) => {
    if (newVal && newVal.length === 2) {
      searchForm.logExecuteTimeBegin = newVal[0]
      searchForm.logExecuteTimeEnd = newVal[1]
    } else {
      searchForm.logExecuteTimeBegin = ''
      searchForm.logExecuteTimeEnd = ''
    }
  })

// 表格配置
const {
  columns,
  columnChecks,
  data,
  loading,
  pagination,
  getData,
  searchParams,
  resetSearchParams,
  handleSizeChange,
  handleCurrentChange,
  refreshData
} = useTable({
  core: {
    apiFn: apiLogLoginPageDataUsingPost,
    apiParams: {
      body: {
        logType: undefined,
        logUserName: '',
        logIp: '',
        logExecuteTimeBegin: '',
        logExecuteTimeEnd: '',
        current: 1,
        size: 10
      } as ApiLogLoginBoApiLogLoginPageData & { current: number; size: number }
    },
    paginationWrapper: 'body',
    columnsFactory: () => [
      { type: 'index', width: 60, label: '序号' },
      { prop: 'logUserName', label: '用户姓名', width: 120 },
      { 
        prop: 'logExecuteTime', 
        label: '操作时间', 
        width: 160,
        formatter: (row) => {
          return formatDateTime(row.logExecuteTime)
        }
      },
      { 
        prop: 'logType', 
        label: '登录类型', 
        width: 100,
        formatter: (row) => {
          return getLogTypeText(row.logType)
        }
      },
      { prop: 'logIp', label: 'IP地址', width: 140 },
      { 
        prop: 'logUserAgent', 
        label: 'User Agent', 
        minWidth: 200,
        formatter: (row) => {
          return h(
            'div',
            {
              class: 'user-agent-cell',
              style: 'white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'
            },
            row.logUserAgent
          )
        }
      },        
      { 
        prop: 'uaIsMobile', 
        label: '是否移动平台', 
        width: 120,
        formatter: (row) => {
          return getDeviceTypeText(row.uaIsMobile)
        }
      },
{
        prop: 'operation',
        label: '详情',
        width: 120,
        fixed: 'right',
        formatter: (row) => h(
          'el-button',
          {
            type: 'primary',
            link: true,
            onClick: () => showDetail(row.id),
            title: '查看详情',
            style: {
              backgroundColor: '#f5f7fa', 
              border: 'none',
              padding: '4px 8px',
              borderRadius: '4px'
            }
          },
          h(View, { 
            style: { 
              width: '1em', 
              height: '1em', 
              verticalAlign: 'middle',
              color: '#666' 
            } 
          })
        )
      }
    ]
  },
  hooks: {
    onSuccess: (data) => {
    },
    onError: (error) => {
      console.error('数据获取失败:', error)
    }
  }
})

  // 查询
  const handleSearch = () => {
    searchParams.body.logUserName = searchForm.logUserName || undefined
    searchParams.body.logIp = searchForm.logIp || undefined
    searchParams.body.logExecuteTimeBegin = searchForm.logExecuteTimeBegin || undefined
    searchParams.body.logExecuteTimeEnd = searchForm.logExecuteTimeEnd || undefined
    searchParams.body.logType = searchForm.logType !== null ? searchForm.logType : undefined
    searchParams.body.current = 1
    getData()
  }

  // 重置
  const handleReset = () => {
    searchForm.logUserName = ''
    searchForm.logIp = ''
    searchForm.logExecuteTimeBegin = ''
    searchForm.logExecuteTimeEnd = ''
    searchForm.logType = null
    searchDateRange.value = ['', '']
    
    resetSearchParams()
    // 确保重置后的参数正确
    searchParams.body.logType = undefined
    searchParams.body.logUserName = ''
    searchParams.body.logIp = ''
    searchParams.body.logExecuteTimeBegin = ''
    searchParams.body.logExecuteTimeEnd = ''
    getData()
  }

  // 显示详情
  const showDetail = async (id: number) => {
    try {
      const res = await apiLogLoginGetDataUsingPost({
        body: {
          id
        } as ApiLogLoginBoApiLogLoginGetData
      })
      
      // 检查响应结构
      if (res) {
        // 判断返回的数据结构类型
        if (res.hasOwnProperty('id') && res.hasOwnProperty('logUserId')) {
          // 直接返回了数据对象
          detailData.value = res
        } else if (res.hasOwnProperty('data') && res.data) {
          // 返回了包装对象
          detailData.value = res.data
        } else {
          // 其他情况
          detailData.value = res
        }
        
        detailDialogVisible.value = true
      } else {
        console.error('获取登录日志详情失败: 返回空数据')
      }
    } catch (error) {
      console.error('获取登录日志详情异常:', error)
    }
  }
  // 初始化数据
  onMounted(() => {
    getData()
  })
</script>

<style scoped lang="scss">
.login-log-page {
  .search-bar {
    background-color: var(--el-bg-color-overlay);
    padding: 18px 18px 0;
    border-radius: 4px;
    
    :deep(.el-form-item) {
      margin-right: 16px;
      margin-bottom: 16px;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 500;
      color: var(--el-text-color-regular);
    }
    
    .search-item {
      width: 220px;
    }
  }
  
  :deep(.el-drawer) {
    border-radius: 8px 0 0 8px;
  }
  
  :deep(.el-drawer__header) {
    border-bottom: 1px solid var(--el-border-color-light);
    padding: 16px 20px;
    margin-bottom: 0;
  }
  
  :deep(.el-drawer__body) {
    padding: 20px;
  }
  
  :deep(.el-drawer__footer) {
    border-top: 1px solid var(--el-border-color-light);
    padding: 16px 20px;
  }
  
  .detail-content {
    padding: 20px 0;
  }
  
  // 修改User Agent单元格样式
  :deep(.el-table__cell.user-agent-cell) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }
  
  // 添加表格样式来消除多余的空白
  :deep(.el-table) {
    // 移除默认的边距和填充
    margin: 0;
    padding: 0;
    
    // 设置表格单元格的内边距
    :deep(.el-table__cell) {
      padding: 8px 0; // 减少垂直内边距
    }
    
    // 设置表格头的样式
    :deep(.el-table__header-wrapper) {
      :deep(.el-table__header) {
        :deep(.el-table__cell) {
          padding: 8px 0; // 减少头部单元格的内边距
        }
      }
    }
    
    // 设置表格行的样式
    :deep(.el-table__body-wrapper) {
      :deep(.el-table__row) {
        :deep(.el-table__cell) {
          padding: 8px 0; // 减少行单元格的内边距
        }
      }
    }
  }
}
</style>